package net.wantongtech.xa.uploadbasicinfo.service;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.refundRestitution.RestitutionDownloadRequest;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;


/**
 * 下载缺失的退费数据包服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/14
 */
@Service
@Slf4j
public class DownloadMissingRefundDataService {

    /**
     * 本地存储路径
     */
    private static final String LOCAL_STORE_PATH = "C:\\refundStorePath";

    @PostConstruct
    public void init() {
        File file = new File(LOCAL_STORE_PATH);
        if (!file.exists() && !file.mkdirs()) {
            throw new IllegalStateException(String.format("文件路径：%s，创建失败", file));
        }
    }

    public void download() {
        LocalDate startDate = LocalDate.parse("2020-02-23");
        LocalDate endDate = LocalDate.now();
        LocalDate temp = startDate;
        while (temp.compareTo(endDate) <= 0) {
            try {
                String version = temp.toString("yyyyMMdd");
                log.info("开始请求下载版本号：{}", version);
                RestitutionDownloadRequest request = new RestitutionDownloadRequest();
                request.setVersion(version);
                LwClientHelper.prepareFilename(request);
                File file = LwClientHelper.downLoad(request, LOCAL_STORE_PATH);
                log.info("版本号：{}，下载文件：{}", version, file.getAbsoluteFile());
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } catch (ApiRequestException e) {
                log.error(e.getMessage());
            }
            temp = temp.plusDays(1);
        }
    }
}
